<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" append-to-body width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="宗地编号" prop="landNo">
            <el-input v-model="formData.landNo" placeholder="请输入宗地编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="土地证号" prop="landCertificate">
            <el-input v-model="formData.landCertificate" placeholder="请输入土地证号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="宗地坐落" prop="landLocation">
            <el-input v-model="formData.landLocation" placeholder="请输入宗地坐落" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="所属区县" prop="landDistrict">
            <el-input v-model="formData.landDistrict" placeholder="请输入所属区县" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属乡镇" prop="landTownship">
            <el-input v-model="formData.landTownship" placeholder="请输入所属乡镇" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属村" prop="landVillage">
            <el-input v-model="formData.landVillage" placeholder="请输入所属村" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="面积" prop="landArea">
            <el-input v-model="formData.landArea" placeholder="请输入面积" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="征收标准" prop="levyStandards">
            <el-input
              v-model="formData.levyStandards"
              placeholder="请输入征收标准（元/平方米*年）"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="权利性质" prop="landQlxz">
            <el-input v-model="formData.landQlxz" placeholder="请输入权利性质" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批准用途" prop="landApprovedUse">
            <el-input v-model="formData.landApprovedUse" placeholder="请输入批准用途" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际用途" prop="landActualUse">
            <el-input v-model="formData.landActualUse" placeholder="请输入实际用途" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="土地级别" prop="landLevel">
            <el-input v-model="formData.landLevel" placeholder="请输入土地级别" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="不动产单元号" prop="landBdcdyh">
            <el-input v-model="formData.landBdcdyh" placeholder="请输入不动产单元号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="坐标" prop="landCoordinate">
            <!-- <UploadFile v-model="formData.landCoordinate" /> -->
            <el-upload
              v-model:file-list="coordinateFileList"
              action=""
              drag
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :auto-upload="false"
              accept=".shp,.zip"
              :on-change="openFile"
              :on-remove="handleRemove"
              ref="shpUpload"
            >
              <el-button type="success">选择或拖拽shp/zip文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="坐标" prop="landCoordinate">
            <el-input
              type="textarea"
              v-model="formData.landCoordinate"
              disabled
              placeholder="请上传坐标"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYS_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="地块档案" name="landFile">
        <LandFileForm ref="landFileFormRef" :belong-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="权利人信息" name="obligee">
        <ObligeeForm ref="obligeeFormRef" :land-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-hasPermi="['zszx:land:update']">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { LandApi, LandVO } from '@/api/zszx/land'
import LandFileForm from './components/LandFileForm.vue'
import ObligeeForm from './components/ObligeeForm.vue'
import { genFileId } from 'element-plus'
import { openShp, readShpZip } from "@/utils/gisTool";
const { proxy } = getCurrentInstance();

/** 宗地信息 表单 */
defineOptions({ name: 'LandForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  landNo: undefined,
  landCertificate: undefined,
  landLocation: undefined,
  landDistrict: undefined,
  landTownship: undefined,
  landVillage: undefined,
  landArea: undefined,
  levyStandards: undefined,
  landQlxz: undefined,
  landApprovedUse: undefined,
  landActualUse: undefined,
  landLevel: undefined,
  landBdcdyh: undefined,
  landCoordinate: undefined,
  remark: undefined,
  status: undefined
})
const formRules = reactive({
  landNo: [{ required: true, message: '宗地编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('landFile')
const landFileFormRef = ref()
const obligeeFormRef = ref()


const coordinateFileList = ref([]);//坐标
/** 坐标文件个数超限操作 */
function handleExceed(files) {
  console.log(files)
  proxy.$refs.shpUpload.clearFiles();
  formData.value.landCoordinate = undefined;
  const file = files[0]
  file.uid = genFileId()
  proxy.$refs.shpUpload.handleStart(file)
}
/** 上传坐标文件操作 */
async function openFile(file) {
  console.log('file', file)
  let extension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase();
  if (extension == "zip") {
    let coor = JSON.stringify(await readShpZip(file));
    formData.value.landCoordinate = coor 
  } else if (extension == "shp") {
    let coor = JSON.stringify(await openShp(file));
    formData.value.landCoordinate = coor 
  }
}
/** 移除坐标操作 */
function handleRemove(file, uploadFiles) {
  formData.value.landCoordinate = undefined;
  proxy.$refs.shpUpload.clearFiles();
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await LandApi.getLand(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await landFileFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'landFile'
    return
  }
  try {
    await obligeeFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'obligee'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as LandVO
    // 拼接子表的数据
    data.landFiles = landFileFormRef.value.getData()
    data.obligees = obligeeFormRef.value.getData()
    if (formType.value === 'create') {
      await LandApi.createLand(data)
      message.success(t('common.createSuccess'))
    } else {
      await LandApi.updateLand(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    landNo: undefined,
    landCertificate: undefined,
    landLocation: undefined,
    landDistrict: undefined,
    landTownship: undefined,
    landVillage: undefined,
    landArea: undefined,
    levyStandards: undefined,
    landQlxz: undefined,
    landApprovedUse: undefined,
    landActualUse: undefined,
    landLevel: undefined,
    landBdcdyh: undefined,
    landCoordinate: undefined,
    remark: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}
</script>
